package com.jiao.spring_es.client;


import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

@Configuration
public class ElasticSearchClientConnect {

    private int port;

    private String ip;

    private String username;

    private String password;

    /**
     * 创建rest客户端
     */
    private final RestHighLevelClient restClient;


    public ElasticSearchClientConnect(@Value("${elasticsearch.port}") int port,
                                      @Value("${elasticsearch.ip}") String ip,
                                      @Value("${elasticsearch.username}") String username,
                                      @Value("${elasticsearch.password}") String password) {
        this.port = port;
        this.ip = ip;
        this.username = username;
        this.password = password;

        if (ip == null || ip.isEmpty()) {
            throw new IllegalArgumentException("Elasticsearch IP address cannot be null or empty");
        }
        if (port <= 0) {
            throw new IllegalArgumentException("Elasticsearch port must be a positive number");
        }

        this.restClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost(ip, port, "http"))
                        .setHttpClientConfigCallback(httpAsyncClientBuilder ->
                                httpAsyncClientBuilder.setDefaultCredentialsProvider(createCredentialsProvider(username, password)))
        );
//        logger.info("Elasticsearch client initialized with IP: {}, Port: {}", ip, port);
    }

    private BasicCredentialsProvider createCredentialsProvider(String username, String password) {
        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        return credentialsProvider;
    }


    public RestHighLevelClient restClient() {
        return restClient;
    }

    public void close() throws IOException {
        if (restClient != null) {
            restClient.close();
        }
    }
}
